package com.ruoyi.demo.controller.app;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.demo.domain.AuctionUser;
import com.ruoyi.demo.service.IAuctionUserService;
import com.ruoyi.demo.service.ITWxUserService;
import com.ruoyi.demo.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "小程序-用户")
@RestController
@RequestMapping("/app/user")
@Slf4j
public class AppAuctionUserController extends BaseController {
    @Autowired
    private IAuctionUserService auctionUserService;
    @Autowired
    private ITWxUserService wxUserService;

    @ApiOperation("查询用户列表")
    @GetMapping("/list")
    public TableDataInfo list(AuctionUser auctionUser) {
        startPage();
        List<AuctionUser> list = auctionUserService.selectAuctionUserList(auctionUser);
        return getDataTable(list);
    }

    @ApiOperation("获取用户详细信息")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return success(auctionUserService.selectAuctionUserByUserId(userId));
    }

    @ApiOperation("新增用户")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AuctionUser auctionUser) {
        return toAjax(auctionUserService.insertAuctionUser(auctionUser));
    }

    @ApiOperation("修改用户")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AuctionUser auctionUser) {
        return toAjax(auctionUserService.updateAuctionUser(auctionUser));
    }

    @ApiOperation("删除用户")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(auctionUserService.deleteAuctionUserByUserIds(userIds));
    }


    @Operation(summary = "获取微信openid")
    @Parameter(name = "code", description = "微信登录code", required = true)
    @GetMapping("/wx/openid")
    public AjaxResult getWxOpenid(@RequestParam String code) {
        try {
            String openid = wxUserService.getOpenid(code);
            if (openid == null) {
                return AjaxResult.error("获取openid失败");
            }

            HashMap<String, Object> data = new HashMap<>();
            data.put("openid", openid);
            return AjaxResult.success("获取openid成功", data);
        } catch (Exception e) {
            log.error("获取微信openid异常", e);
            return AjaxResult.error("获取openid失败");
        }
    }

    @ApiOperation("小程序用户登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody AuctionUser user) {
        try {
            // 验证手机号是否为空
            if (user.getPhone() == null || user.getPhone().isEmpty()) {
                return error("手机号不能为空");
            }

            AuctionUser existUser = auctionUserService.selectAuctionUserByPhone(user.getPhone());

            if (existUser == null) {
                // 新用户注册
                user.setCreateTime(new Date());
                user.setStatus("0");
                auctionUserService.insertAuctionUser(user);
                existUser = user;
            } else {
                // 更新用户信息
                if (user.getNickName() != null) {
                    existUser.setNickName(user.getNickName());
                }
                if (user.getAvatar() != null) {
                    existUser.setAvatar(user.getAvatar());
                }
                if (user.getGender() != null) {
                    existUser.setGender(user.getGender());
                }
                if (user.getOpenid() != null) {
                    existUser.setOpenid(user.getOpenid());
                }
            }

            existUser.setLastLoginTime(new Date());
            existUser.setLastLoginIp(IpUtils.getIpAddr());
            auctionUserService.updateAuctionUser(existUser);

            String token = TokenUtils.generateToken(existUser);

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", existUser);

            return success(result);
        } catch (Exception e) {
            log.error("用户登录异常", e);
            return error("登录失败");
        }
    }
}
